package jfmultitplengine.thymeleaf;

import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ISource;
import com.jfinal.template.source.ISourceFactory;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;


/**
 * @author 张天笑
 * @time 2018/12/28 22:08
 */
public class ThymeleafRender extends Render {

    public ThymeleafRender(String baseTempaltePath, String view, ISourceFactory sourceFactory) {
        this.baseTempaltePath = baseTempaltePath;
        this.view = view;
        this.sourceFactory = sourceFactory;
    }

    public ISourceFactory sourceFactory;
    public String baseTempaltePath;


    @Override
    public void render() {
        HttpServletRequest req = this.request;
        HttpServletResponse resp = this.response;

        if (view.startsWith("/") && baseTempaltePath.equals("/")) {
            baseTempaltePath = "";
        }

        //
        ISource iSource = sourceFactory.getSource(baseTempaltePath, view, getEncoding());
        String content = iSource.getContent().toString();
        TemplateEngine teg = new TemplateEngine();

        HashMap<String, Object> data = new HashMap<>();

        //request
        Enumeration<String> attributeNames = req.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement();
            Object value = req.getAttribute(name);
            data.put(name, value);
        }


        Context ctx = new Context(Locale.getDefault(), data);
        try {
            PrintWriter writer = resp.getWriter();
            teg.process(content, ctx, writer);
            writer.flush();
        } catch (Exception e) {
            throw new RenderException(e);
        }


    }
}
